﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WorkStation.Frameworks.Core.Extensions
{
    public static class TypeExtensions
    {
        /// <summary>
        /// * 获取所有基类（不包括object）
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static List<Type> GetAllBaseType(this Type type)
        {
            List<Type> res = new List<Type>();

            res.Add(type);

            if (type.BaseType != typeof(object))
            {
                res.AddRange(type.BaseType.GetAllBaseType());
            }

            return res;
        }

        private static ConcurrentDictionary<Type, Dictionary<string, Tuple<int, string>>> _CACHE = new ConcurrentDictionary<Type, Dictionary<string, Tuple<int, string>>>();

        /// <summary>
        /// * 获取枚举信息
        /// </summary>
        /// <param name="type">枚举类型</param>
        /// <returns>KEY：枚举的值名称，int：枚举值 string：描述</returns>
        public static Dictionary<string, Tuple<int, string>> GetEnumInfo(this Type type)
        {
            if (!type.IsEnum) { return null; }

            return _CACHE.GetOrAdd(type, t =>
            {
                var names = Enum.GetNames(t);
                var values = Enum.GetValues(t);

                Dictionary<string, Tuple<int, string>> res = new Dictionary<string, Tuple<int, string>>();

                for (int i = 0; i < names.Length; i++) 
                {
                    res.Add(names[i], new Tuple<int, string>(Convert.ToInt32(values.GetValue(i)), t.GetField(names[i]).GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false).FirstOrDefault().Change(v => (v as System.ComponentModel.DescriptionAttribute).Description)));
                }

                return res;
            });
        }
    }
}
